﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Helper.Infrastructure.Login;
using Helper.Infrastructure.Session;
using Helper.Business.Implementation;
using Helper.Business.Repository;
using Helper.Core.Entity;
using Helper.Metadata;


namespace Helper.Controllers
{
    public class LoginController : Controller
    {
        IUserRepository _userRepository;

        public LoginController()
        {
            if(_userRepository == null)
                _userRepository = new UserRepository();
        }
        
        //
        // GET: /Login/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult SecurityException()
        {
            return View();
        }

        public ActionResult WrongUserOrPassword()
        {
            return View();
        }

        public ActionResult AlreadyLogged()
        {
            return View();
        }

        public ActionResult AuthUser()
        {
            UserSession _session = UserSession.GetInstance;
            if (!SessionAuth.VerifySession(_session))
                return View(new Metadata.LoginRequestMetadata());
            return RedirectToAction("AlreadyLogged", "Login");
        }


        [HttpPost]
        public JsonResult AuthUser(Helper.Infrastructure.Login.LoginRequest Request)
        {
            try
            {
                UserSession _session = UserSession.GetInstance;

                if (!SessionAuth.VerifySession(_session))
                {
                    Core.Entity.User user = _userRepository.FindByUsernameAndPassword(Request.Username, Request.EncryptedPassword);

                    if (user != null)
                    {
                        _session.Logged = true;
                        _session.Id = user.Id;
                        _session.Username = user.Name;
                        _session.SecurityKey = UserSession.SECURITYKEY;

                        return Json(new { success = true });
                    }
                    else
                        return Json(new { success = false, errors = new {reason ="Usuário e/ou Senha inválido(s)!"} });
                }
                else
                {
                    return Json(new { success = false });
                }
            }
            catch(Exception ex)
            {
                return Json(new { success = false, errors = new { reason = ex.Message } });
            }
        }
        
        public ActionResult LogOff()
        {
            if (SessionAuth.VerifySession(UserSession.GetInstance))
            {
                UserSession.GetInstance = new UserSession();
            }

            return View();
        }

    }
}
